var express = require('express');
var router = express.Router();
var mupload = require('mill-upload-fornode');
var path = require('path');

// 增删改差的功能
/* GET users listing. */
router.get('/', function(req, res, next) {
	msql.query('select * from mm_car',function (r,f) {
		// res.json(r);
		res.render('car_table',{data:r});
	});
  // res.send("汽车模块的主页");
});

// window.location.href = "car/add_car_view";
//添加汽车界面
router.get('/add_car_view', function(req, res, next) {
	
	res.render('add_car',{});

});
//删除汽车
router.get('/car_delete_handler', function(req, res, next) {
	
	msql.query(`delete from mm_car where c_id=?`
		,[req.param('id')],
		function (r,f) {
			res.redirect('/car');
		});

});
//更新界面
router.get('/car_update_view', function(req, res, next) {
	
	msql.query(`select * from mm_car where c_id = ?`
		,[req.param('id')],
		function (r,f) {
			res.render('car_update',{data:r});
		});

});
//更新界面
router.post('/car_update_handler', function(req, res, next) {
	var cid=req.param('c_id');
	delete req.body["c_id"];
	msql.query(`update mm_car set  ? where c_id = ?`
		,[req.body,cid],
		function (r,f) {
			res.redirect('/car');
		});

});
router.post('/add_car_handler', function(req, res, next) {
	mupload.parseForm(req,'./public/images','mm'+(new Date()).getTime())
	.then(function(fileds){
		var img_path = path.resolve(fileds.c_img);
msql.query(`insert into mm_car (c_band,c_color,c_price,c_img) values (?,?,?,?)`,
		[fileds.c_band[0],fileds.c_color[0],fileds.c_price[0],path.basename(img_path)],
		function (r,f) {
			console.log(r.insertId);
			res.redirect('/car');
		});


		});
// {"c_band":["本田"],"c_color":["1"],"c_price":["4322"],"c_img":"D:\\gits\\express_demo\\public\\images\\mm1522826949803a701su2093595565650.jpg"}

	
});

router.get('/upload', function(req, res, next) {
	res.render('upload_view',{});
});



router.post('/upload_test', function(req, res, next) {
	mupload.parseForm(req,"./public/images",
		"mm"+(new Date()).getTime())
	.then(function(fileds){
		res.json(fileds);
	});
});

module.exports = router;

/*
request
	- body 所有post来的参数
	- param() 获取get参数
response
	- send 发送文本信息
	- render(视图名,{})  views/视图名.ejs
	- json 发送json文本
	- redirect 重定向
*/